/**
 * 简化的构建产物分析脚本
 */

import fs from 'fs'
import path from 'path'
import { fileURLToPath } from 'url'

const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)

/**
 * 格式化字节大小
 */
function formatBytes(bytes) {
  if (bytes === 0) return '0 B'
  
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

/**
 * 分析构建产物
 */
function analyzeBuild() {
  const distPath = path.join(__dirname, '../dist')
  
  if (!fs.existsSync(distPath)) {
    console.error('❌ dist 目录不存在，请先运行构建命令')
    return
  }
  
  console.log('📊 构建产物分析\n')
  
  const stats = {
    totalSize: 0,
    files: [],
    categories: {
      js: { size: 0, count: 0 },
      css: { size: 0, count: 0 },
      html: { size: 0, count: 0 },
      other: { size: 0, count: 0 }
    }
  }
  
  function scanDirectory(dir, relativePath = '') {
    const files = fs.readdirSync(dir)
    
    files.forEach(file => {
      const filePath = path.join(dir, file)
      const relativeFilePath = path.join(relativePath, file)
      const stat = fs.statSync(filePath)
      
      if (stat.isDirectory()) {
        scanDirectory(filePath, relativeFilePath)
      } else {
        const size = stat.size
        const ext = path.extname(file).toLowerCase()
        
        stats.totalSize += size
        stats.files.push({
          path: relativeFilePath,
          size: size,
          sizeFormatted: formatBytes(size)
        })
        
        // 分类统计
        if (['.js', '.mjs'].includes(ext)) {
          stats.categories.js.size += size
          stats.categories.js.count++
        } else if (ext === '.css') {
          stats.categories.css.size += size
          stats.categories.css.count++
        } else if (ext === '.html') {
          stats.categories.html.size += size
          stats.categories.html.count++
        } else {
          stats.categories.other.size += size
          stats.categories.other.count++
        }
      }
    })
  }
  
  scanDirectory(distPath)
  
  // 排序文件（按大小降序）
  stats.files.sort((a, b) => b.size - a.size)
  
  // 输出结果
  console.log(`📦 总大小: ${formatBytes(stats.totalSize)}`)
  console.log(`📄 文件数量: ${stats.files.length}\n`)
  
  console.log('📊 分类统计:')
  Object.entries(stats.categories).forEach(([category, data]) => {
    if (data.count > 0) {
      const percentage = ((data.size / stats.totalSize) * 100).toFixed(1)
      console.log(`  ${category.toUpperCase()}: ${formatBytes(data.size)} (${data.count} 文件, ${percentage}%)`)
    }
  })
  
  console.log('\n📋 最大的文件:')
  stats.files.slice(0, 10).forEach((file, index) => {
    const percentage = ((file.size / stats.totalSize) * 100).toFixed(1)
    console.log(`  ${index + 1}. ${file.path} - ${file.sizeFormatted} (${percentage}%)`)
  })
  
  // 性能建议
  console.log('\n💡 性能建议:')
  if (stats.categories.js.size > 500 * 1024) {
    console.log('  ⚠️  JavaScript 文件较大，考虑进一步代码分割')
  }
  if (stats.categories.css.size > 100 * 1024) {
    console.log('  ⚠️  CSS 文件较大，考虑移除未使用的样式')
  }
  if (stats.totalSize > 2 * 1024 * 1024) {
    console.log('  ⚠️  总体积较大，考虑启用更激进的压缩')
  } else {
    console.log('  ✅ 构建产物大小合理')
  }
  
  // 保存报告
  const report = {
    timestamp: new Date().toISOString(),
    totalSize: stats.totalSize,
    totalSizeFormatted: formatBytes(stats.totalSize),
    fileCount: stats.files.length,
    categories: stats.categories,
    largestFiles: stats.files.slice(0, 10)
  }
  
  const reportPath = path.join(__dirname, '../performance-report.json')
  fs.writeFileSync(reportPath, JSON.stringify(report, null, 2))
  console.log(`\n📊 详细报告已保存到: performance-report.json`)
}

// 运行分析
analyzeBuild()